package com.stylefeng.guns.biz.acct;

import com.stylefeng.guns.common.bo.AuthUserBo;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.persistence.dao.WebuserMapper;
import com.stylefeng.guns.common.persistence.model.Webuser;
import com.stylefeng.guns.common.service.redis.RedisClient;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.support.RestConstant;
import com.stylefeng.guns.core.util.IdGenerator;
import com.stylefeng.guns.modular.system.service.IWebuserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author carloszhang
 */
@Slf4j
@Component("loginBizImpl")
public class LoginBizImpl {

    @Autowired
    private WebuserMapper webuserMapper;

    @Autowired
    private RedisClient redisClient;


    @Autowired
    private IWebuserService iWebuserService;

    public Webuser validateLoginUser(String telno, String cipher) {
        Webuser webuser =iWebuserService.qryExistWebUserByTelno(telno);
        boolean isValid = iWebuserService.validLoginCipher(webuser, cipher);
        if (!isValid) {
            throw new GunsException(BizExceptionEnum.LOGIN_CIPHER_ERROR);
        }
        return webuser;
    }

    public AuthUserBo LoginCacheUser(Webuser webuser) {
        String token = IdGenerator.get32UUID() + IdGenerator.getId();//用户登录token
        AuthUserBo authUserBo = new AuthUserBo();
        authUserBo.setAuthKey(token);
        authUserBo.setId(webuser.getId());
        boolean flag = redisClient.set(RestConstant.AUTH_USER_CACHE_KEY + token, authUserBo);
        if (!flag) {
            throw new GunsException(BizExceptionEnum.USER_LOGIN_ERROR);
        }
        return authUserBo;
    }

    public AuthUserBo getCacheUser(String token) {
        AuthUserBo authUserBo = redisClient.get(RestConstant.AUTH_USER_CACHE_KEY + token, AuthUserBo.class);
        return authUserBo;
    }

    public void delCacheUser(String accessToken) {
        boolean flag = redisClient.del(RestConstant.AUTH_USER_CACHE_KEY + accessToken);
        if (flag) {
            throw new GunsException(BizExceptionEnum.USER_LOGOUT_ERROR);
        }
    }

    public boolean registerUser(String mobileNo, String cipher) {
        Webuser tmp = new Webuser();
        tmp.setTelno(mobileNo);
        Webuser webuser = webuserMapper.selectByTelNo(tmp);
        if (webuser != null) {
            throw new GunsException(BizExceptionEnum.USER_ALREADY_EXIST);
        }
        return iWebuserService.registerUser(mobileNo, cipher);//注册用户,加上事务
    }

    public boolean forgetLoginCipher(String mobileNo, String cipher) {
        return iWebuserService.forgetLoginCipherUser(mobileNo, cipher);//注册用户,加上事务
    }

}
